package com.choudou5.solr.utils.oauth;

import com.alibaba.fastjson.JSON;
import com.choudou5.solr.util.exception.BizException;
import com.choudou5.solr.util.BeanMapper;
import com.choudou5.solr.util.ConfigUtil;
import com.choudou5.solr.util.JsonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.*;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @name Oauth 配置解析工具类
 * @author choudou5
 * @date 2018-7-16
 */
public class OauthParseUtil {


    private static final Logger logger = LoggerFactory.getLogger(ConfigUtil.class);

    private static List<OauthBean> OAUTH_LIST = null;

    public static void main(String[] args) {
        System.out.println(JSON.toJSONString(getOauthList()));
    }

    public static List<OauthBean> getOauthList(){
        checkInit();
        return OAUTH_LIST;
    }

    public static OauthBean getOauthBean(String appId) throws BizException{
        checkInit();
        for (OauthBean bean : OAUTH_LIST) {
            if(bean.getAppId().equals(appId))
                return bean;
        }
        throw new BizException("不存在 appId:"+appId+"的网站");
    }

    private static void checkInit(){
        if(OAUTH_LIST == null)
            parserXML("conf/oauth.xml");
    }

    /**
     * 解析xml文件
     * @param path
     * @return
     */
    private static void parserXML(String path) {
        InputStream is = OauthParseUtil.class.getClassLoader().getResourceAsStream(path);
        if(is == null){
            logger.error(path + " 文件不存在！");
            throw new RuntimeException(path + " 文件不存在！");
        }
        OAUTH_LIST = new ArrayList<>();
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        try {
            DocumentBuilder builder = dbFactory.newDocumentBuilder();
            Document doc = builder.parse(is);
            NodeList configList = doc.getElementsByTagName("config");
            if (configList != null && configList.getLength() > 0) {
                for (int i = 0; i < configList.getLength(); i++) {
                    Element config = (Element) configList.item(i);
                    OauthBean bean = buildOauthBean(config.getAttributes());
                    if(bean != null)
                        OAUTH_LIST.add(bean);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(path + "， 解析xml失败.", e);
        }
        logger.info("解析完毕");
    }

    private static OauthBean buildOauthBean(NamedNodeMap attrs){
        OauthBean bean = null;
        int len = attrs.getLength();
        if(len > 0){
            Map<String, Object> map = new HashMap<>();
            Node attr = null;
            for (int i = 0; i < len; i++) {
                attr = attrs.item(i);
                map.put(attr.getNodeName(), attr.getNodeValue());
            }
            logger.info("oauthBean: " + JsonUtil.toStr(map));
            bean = BeanMapper.map(map, OauthBean.class);
        }
        return bean;
    }

}
